package com.ranga.mselfcare;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.ranga.mselfcare.config.Config;
import com.ranga.mselfcare.entity.Credit;
import com.ranga.mselfcare.services.BalanceService;

@SuppressLint("HandlerLeak")
public class BalanceActivity extends Activity {

	private int status = Config.PROGRESS_STOPPED;
	private final String TAG = "BalanceActivity";
	private String phoneNumber = "";
	private String token = "";
	private ProgressDialog progressDialog;
	private Credit credit;
	private TextView tViewCredit;
	private TextView tViewCreditAsOf;
	private TextView tViewEWallet;
	private TextView tViewEWalletAsOf;
	private TextView tViewCreditLastUpdateOn;
	private TextView tViewEWalletLastUpdateOn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_get_balance);
		
		tViewCredit = (TextView) findViewById(R.id.tvCredit);
		tViewCreditAsOf = (TextView) findViewById(R.id.tvCreditAsOf);
		tViewCreditLastUpdateOn = (TextView) findViewById(R.id.tvCreditLastUpdateOn);
		tViewEWallet = (TextView) findViewById(R.id.tvEWallet);
		tViewEWalletAsOf = (TextView) findViewById(R.id.tvEWalletAsOf);
		tViewEWalletLastUpdateOn = (TextView) findViewById(R.id.tvEWalletLastUpdateOn);
		
		
		initializeDataFromSharedPreference();
		progressDialog = new ProgressDialog(this);
		if (isNetworkAvailable()) {
			if (status == Config.PROGRESS_STOPPED) {
				Intent getBalanceIntent = new Intent(BalanceActivity.this, BalanceService.class);
				Messenger resultMessenger = new Messenger(
						serviceResultHandler);
				Messenger progressMessenger = new Messenger(
						progressHandler);
				Bundle bundle = new Bundle();
				bundle.putString(Config.PHONE_NUMBER, phoneNumber);
				bundle.putString(Config.TOKEN, token);
				try {
					Log.w(TAG, "inside try");
					getBalanceIntent.putExtras(bundle);
					getBalanceIntent.putExtra(Config.RESULT_MESSENGER,
							resultMessenger);
					getBalanceIntent.putExtra(Config.PROGRESS_MESSENGER,
							progressMessenger);
					startService(getBalanceIntent);
				} catch (SecurityException e) {
					Log.w(TAG, "Unable to start get login service: "
							+ e.toString());
				}
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		hideProgressDialog();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (status == Config.PROGRESS_STARTED) {
			progressDialog.setMessage(this.getString(R.string.getting_balance));
			progressDialog.show();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(Config.STATUS, status);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		status = savedInstanceState.getInt(Config.STATUS);
	}
	
	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

		boolean networkAvailable = false;

		if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
			networkAvailable = true;
		} else {
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
			alertDialog.setTitle(getString(R.string.alert));
			alertDialog
					.setMessage(getString(R.string.no_internet_connectivity));
			alertDialog.setPositiveButton(getString(R.string.okay),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							startActivity(new Intent(
									WifiManager.ACTION_PICK_WIFI_NETWORK));
						}
					});
			alertDialog.show();
		}
		return networkAvailable;
	}
	
	private Handler progressHandler = new Handler() {
		public void handleMessage(Message message) {

			status = message.arg1;

			switch (status) {

			case Config.PROGRESS_STARTED:
				Log.i(TAG, "Progress Started");
				progressDialog.setMessage(BalanceActivity.this
						.getString(R.string.getting_token));
				progressDialog.show();
				break;
			case Config.PROGRESS_STOPPED:
				Log.i(TAG, "Progress stopped");
				hideProgressDialog();
				showToast(R.string.alert_error_getting_balance);
				status = Config.PROGRESS_STOPPED;
				break;
			case Config.PROGRESS_SUCCESS:
				Log.i(TAG, "Progress success");
				hideProgressDialog();
				status = Config.PROGRESS_STOPPED;
				break;
			}
		};
	};

	private Handler serviceResultHandler = new Handler() {
		public void handleMessage(Message message) {
			Bundle resultBundle = message.getData();
			String response = "";
			int errorCode = 0;
			if (resultBundle.containsKey(Config.RESPONSE)) {
				response = resultBundle.getString(Config.RESPONSE);
			}
			if (resultBundle.containsKey(Config.RESPONSE_ERROR)) {
				errorCode = Integer.parseInt(resultBundle.getString(Config.RESPONSE_ERROR));
			}
			Log.w(TAG, "Response Recieved: " + response);
			if (errorCode == 200) {
				if (!response.contentEquals("")) {
					credit = parseJSonString(response);
				}
				if (!credit.equals(null)) {
					setDataToUi();
				}
			} else if (errorCode == 405) {
				displayErrorMessage(R.string.alert_token_expired);
				startTokenInitializeActivity();
			}
		};
	};
	
	private void hideProgressDialog() {
		if (progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}
	
	private void initializeDataFromSharedPreference() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		token = prefs.getString(Config.TOKEN, "");
		phoneNumber = prefs.getString(Config.PHONE_NUMBER, "");

		if (token.contentEquals("")) {
			Log.e(TAG, "token not saved from previous activity");
			AlertDialog.Builder alertTokenNotRecieved = new AlertDialog.Builder(
					this);
			alertTokenNotRecieved.setTitle(this.getString(R.string.alert));
			alertTokenNotRecieved
					.setMessage(getString(R.string.alert_token_not_saved));
			alertTokenNotRecieved.setPositiveButton(getString(R.string.okay),
					new DialogInterface.OnClickListener() {

			
				@Override
						public void onClick(DialogInterface dialog, int which) {
							startTokenInitializeActivity();
						}
					});
		}
	}
	
	
	private void startTokenInitializeActivity() {
		Intent tokenInitialize = new Intent(BalanceActivity.this, TokenInitializeActivity.class);
		finish();
		startActivity(tokenInitialize);
	}
	
	private Credit parseJSonString(String jsonString) {
		Credit credit = new Credit();
		try {
			JSONObject jsonObject = new JSONObject(jsonString);
			credit.setCredit(jsonObject.getString("Credit"));
			credit.setCreditAsOf(jsonObject.getString("CreditAsOf"));
			credit.seteWallet(jsonObject.getString("EWallet"));
			credit.seteWalletAsOf(jsonObject.getString("EWallatAsOf"));
			credit.setCreditLastUpdateOn(jsonObject.getString("CreditLastUpdateOn"));
			credit.seteWalletLastUpdateOn(jsonObject.getString("EWalletLastUpdateOn"));
			
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return credit;
	}
	
	private void setDataToUi() {
		if (credit.getCredit() != null && !credit.getCredit().contentEquals("null")) {
			tViewCredit.setText(credit.getCredit());
		} else {
			tViewCredit.setText("");
		}
		
		if (credit.getCreditAsOf() != null && !credit.getCreditAsOf().contentEquals("null")) {
			tViewCreditAsOf.setText(credit.getCreditAsOf());
		} else {
			tViewCreditAsOf.setText("");
		}
		
		if (credit.getCreditLastUpdateOn() != null && !credit.getCreditLastUpdateOn().contentEquals("null")) {
			tViewCreditLastUpdateOn.setText(credit.getCreditLastUpdateOn());
		} else {
			tViewCreditLastUpdateOn.setText("");
		}
		
		if (credit.geteWallet() != null && !credit.geteWallet().contentEquals("null")) {
			tViewEWallet.setText(credit.geteWallet());
		} else {
			tViewEWallet.setText("");
		}
		
		if (credit.geteWalletAsOf() != null && !credit.geteWalletAsOf().contentEquals("null")) {
			tViewEWalletAsOf.setText(credit.geteWalletAsOf());
		} else {
			tViewEWalletAsOf.setText("");
		}
		
		if (credit.geteWalletLastUpdateOn() != null && !credit.geteWalletLastUpdateOn().contentEquals("null")) {
			tViewEWalletLastUpdateOn.setText(credit.geteWalletLastUpdateOn());
		} else {
			tViewEWalletLastUpdateOn.setText("");
		}
		
	}
	
	private void showToast(int message) {
		Toast.makeText(this, BalanceActivity.this.getString(message), Toast.LENGTH_SHORT).show();
	}
	
	private void displayErrorMessage(int message) {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(
				BalanceActivity.this);
		alertDialog.setTitle(getString(R.string.alert));
		alertDialog.setMessage(getString(message));
		alertDialog.setPositiveButton(getString(R.string.okay),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		alertDialog.show();
	}
	
	@Override
	public void onBackPressed() {
		Intent inent = new Intent(BalanceActivity.this, MainMenuActivity.class);
		finish();
		startActivity(inent);
	}

}
